#!/usr/bin/env python


import os

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp import util

import packages

from config import TEMPLATES
import pronouncer
import taggers


class Homepage(webapp.RequestHandler):

    def get(self):
        path = os.path.join(TEMPLATES, 'home.html')
        title = 'Pronounce Words'
        html = template.render(path, locals(), debug=True)
        self.response.out.write(html)

    def post(self):
        path = os.path.join(TEMPLATES, 'output.html')
        title = 'Pronounce Words'

        raw = self.request.get('raw')
        full_tagger = taggers.FullTagger.factory()
        tagged = full_tagger.tag(raw)
        tagged = self._flatten(tagged)
        p = pronouncer.Pronouncer()
        pronounced = p.get_prons(raw)

        output = []
        for tag, pron in zip(tagged, pronounced):
            o = (tag[0], tag[1], pron)
            output.append(o)

        html = template.render(path, locals(), debug=True)
        self.response.out.write(html)

    def _flatten(self, tagged):
        flat = []
        for t in tagged:
            flat.extend(t)
        return flat


def main():
    url_mapping = (
        ('.*',  Homepage),
    )
    app = webapp.WSGIApplication(url_mapping, debug=True)
    util.run_wsgi_app(app)


if __name__ == '__main__':
    main()
